package io.renren.modules.work.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ioserver.bean.Union_DataType;
import io.renren.common.utils.R;
import io.renren.modules.basic.entity.*;
import io.renren.modules.basic.service.*;
import io.renren.modules.ioserver.IOServerService;
import io.renren.modules.wcs.entity.DDJJobEntity;
import io.renren.modules.wcs.enums.DDJStatusEnum;
import io.renren.modules.wcs.enums.IOServerEnum;
import io.renren.modules.wcs.service.DDJService;
import io.renren.modules.work.Utils.ManageConstant;
import io.renren.modules.work.Utils.ManagePublicMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: weihongyang
 * @Date: 2019/11/12 14:04
 * @Version 1.0
 */
@Component
@Api(description = "报警接口")
@RequestMapping(value = "warning")
public class RunTaskSchedule {

    private Logger logger = LoggerFactory.getLogger(getClass());
    public static String message="";

    @Autowired
    private MtCcTaskRunInfoDetService mtCcTaskRunInfoDetService;
    @Autowired
    private MtCcTaskRunInfoService mtCcTaskRunInfoService;
    @Autowired
    private DDJService ddjService;
    @Autowired
    private MtCcWarehousPositionRelatService mtCcWarehousPositionRelatService;
    @Autowired
    private MtCcWarehousRankService mtCcWarehousRankService;
    @Autowired
    private MtCcWarehousPositionRelatLogService mtCcWarehousPositionRelatLogService;
    @Autowired
    private MtCcProductService mtCcProductService;
    @Autowired
    private MtCcTaskRunInfoDetLogService mtCcTaskRunInfoDetLogService;
    @Autowired
    private IOServerService ioServerService;
    @Autowired
    private MtCcDeviceCommunLogService mtCcDeviceCommunLogService;
    @Autowired
    private MtCcTaskRunInfoLogService mtCcTaskRunInfoLogService;
    /*@Autowired
    private LtkService ltkService;*/

//    @Scheduled(fixedRate = 1000*3)
    public void test(){
        logger.info("Current Thread : {}", Thread.currentThread().getName());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateFormat = simpleDateFormat.format(date);
        List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDetEntityList = mtCcTaskRunInfoDetService.list();
        for (MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity:mtCcTaskRunInfoDetEntityList) {
            System.out.println(dateFormat+"===="+mtCcTaskRunInfoDetEntity.toString());
        }
    }
/*    @Scheduled(fixedRate = 1000*10)
    public void erptowms(){
        List<LtkEntity> ltkEntities = ltkService.list();
        for (LtkEntity ltkEntity:ltkEntities
             ) {
            Integer productId = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", ltkEntity.getFnumber())).getId();
            MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity=new MtCcTaskRunInfoEntity();
            mtCcTaskRunInfoEntity.setCreateTime(new Date());
            mtCcTaskRunInfoEntity.setUserName("ERP");
            mtCcTaskRunInfoEntity.setSource("ERP");
            mtCcTaskRunInfoEntity.setTaskType(ltkEntity.getCrk());
            if (("一号口").equals(ltkEntity.getCrko())){
                if (ltkEntity.getCrk()==1){
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,"A1"));
                }else {
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,"A1"));
                }
            }
            if (("二号口").equals(ltkEntity.getCrko())){
                if (ltkEntity.getCrk()==1){
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,"A2"));
                }else {
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,"A2"));
                }
            }
            if (("三号口").equals(ltkEntity.getCrko())){
                if (ltkEntity.getCrk()==1){
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,"A3"));
                }else {
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,"A3"));
                }
            }
            if (("四号口").equals(ltkEntity.getCrko())){
                if (ltkEntity.getCrk()==1){
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,"A4"));
                }else {
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,"A4"));
                }
            }
            if (("进货口").equals(ltkEntity.getCrko())){
                if (ltkEntity.getCrk()==1){
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,"B1"));
                }else {
                    mtCcTaskRunInfoEntity.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,"B1"));
                }
            }
            mtCcTaskRunInfoEntity.setModel(ltkEntity.getFnumber());
            mtCcTaskRunInfoEntity.setProductId(productId);
            mtCcTaskRunInfoEntity.setNum(String.valueOf(ltkEntity.getFqty()));
            mtCcTaskRunInfoEntity.setUnit(ltkEntity.getFunitid());
            mtCcTaskRunInfoEntity.setFBillno(ltkEntity.getFbillno());
            mtCcTaskRunInfoEntity.setFBatchNo(ltkEntity.getFbatchno());
            mtCcTaskRunInfoEntity.setFEntryId(ltkEntity.getFentryid());
            mtCcTaskRunInfoEntity.setStatus(0);
            mtCcTaskRunInfoService.save(mtCcTaskRunInfoEntity);
            mtCcTaskRunInfoEntity.setOrderNum(mtCcTaskRunInfoEntity.getId());
            mtCcTaskRunInfoService.updateById(mtCcTaskRunInfoEntity);
            MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLogEntity=new MtCcTaskRunInfoLogEntity();
            mtCcTaskRunInfoLogEntity.setCreateTime(mtCcTaskRunInfoEntity.getCreateTime());
            mtCcTaskRunInfoLogEntity.setUserId(mtCcTaskRunInfoEntity.getUserId());
            mtCcTaskRunInfoLogEntity.setUserName(mtCcTaskRunInfoEntity.getUserName());
            mtCcTaskRunInfoLogEntity.setTaskType(mtCcTaskRunInfoEntity.getTaskType());
            mtCcTaskRunInfoLogEntity.setTaskCode(mtCcTaskRunInfoEntity.getTaskCode());
            mtCcTaskRunInfoLogEntity.setProductId(mtCcTaskRunInfoEntity.getProductId());
            mtCcTaskRunInfoLogEntity.setModel(mtCcTaskRunInfoEntity.getModel());
            mtCcTaskRunInfoLogEntity.setNum(mtCcTaskRunInfoEntity.getNum());
            mtCcTaskRunInfoLogEntity.setUnit(mtCcTaskRunInfoEntity.getUnit());
            mtCcTaskRunInfoLogEntity.setRemarks(mtCcTaskRunInfoEntity.getRemarks());
            mtCcTaskRunInfoLogEntity.setStatus(0);
            mtCcTaskRunInfoLogService.save(mtCcTaskRunInfoLogEntity);
            ltkService.removeById(ltkEntity);
        }

    }*/

    /**
     * 报警信息接口
     */
    @ApiOperation(value = "报警信息接口",notes = "报警信息接口")
    @RequestMapping(value = "/message")
    public R warningMessage(){
        return R.ok(message);
    }
    @ApiOperation(value = "结束任务接口",notes = "结束任务接口")
    @RequestMapping(value = "/killTask")
    public R killTask(Integer doorway){
        String closeLStart = "";
        String openEndTask= "";
        switch(doorway)
        {
            case 1 :
                closeLStart = IOServerEnum.Cargo_First_OUT_Start.getCollectionPointName();
                openEndTask = IOServerEnum.Cargo_Frist_End.getCollectionPointName();
                break;
            case 2 :
                closeLStart = IOServerEnum.Cargo_Second_OUT_Start.getCollectionPointName();
                openEndTask = IOServerEnum.Cargo_Second_End.getCollectionPointName();
                break;
            case 3 :
                closeLStart = IOServerEnum.Cargo_Third_OUT_Start.getCollectionPointName();
                openEndTask = IOServerEnum.Cargo_Third_End.getCollectionPointName();
                break;
            case 4 :
                closeLStart = IOServerEnum.Cargo_Fourth_OUT_Start.getCollectionPointName();
                openEndTask = IOServerEnum.Cargo_Fourth_End.getCollectionPointName();
                break;
            case 5 :
                closeLStart = IOServerEnum.Cargo_Fifth_OUT_Start.getCollectionPointName();
                openEndTask = IOServerEnum.Cargo_Fifth_End.getCollectionPointName();
                break;
            default :
                closeLStart = null;
                openEndTask = null;
                logger.error("未知平台入口");
        }

        int CLOSELStart=-1;
        int OPENEndTask=-1;
        try {
            CLOSELStart = ioServerService.setTagValue(closeLStart, DDJStatusEnum.FALSE.getDeviceStatus().toString(), 4);
            Thread.sleep(500);
            OPENEndTask = ioServerService.setTagValue(openEndTask, DDJStatusEnum.TRUE.getDeviceStatus().toString(), 4);
            if(CLOSELStart!=0 || OPENEndTask !=0){
                return R.error();
            }
        }catch (Exception e){
            logger.error("在出库的时候，有占位，取消任务失败。");
            return R.error("在出库的时候，有占位，取消任务失败。");
        }
        message="";
        return R.ok();
    }



    /**
     *执行任务
     */
    @Scheduled(fixedRate = 5000*3)
    //@Transactional(rollbackFor = Exception.class)
    public void runTaskInfo() throws Exception {
        int countOfRunning = mtCcTaskRunInfoService.count(new QueryWrapper<MtCcTaskRunInfoEntity>().eq("status", 1));
        if (countOfRunning==0){//当前没有正在执行的任务
            List<MtCcTaskRunInfoEntity> mtCcTaskRunInfoEntis = mtCcTaskRunInfoService
                    .list(new QueryWrapper<MtCcTaskRunInfoEntity>().eq("status", 4).orderByAsc("order_num"));
            if (mtCcTaskRunInfoEntis.size()!=0){
                MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity = mtCcTaskRunInfoEntis.get(0);
                mtCcTaskRunInfoEntity.getId();
                mtCcTaskRunInfoEntity.setStatus(1);//更改任务状态为正在执行
                mtCcTaskRunInfoService.updateById(mtCcTaskRunInfoEntity);
                List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDets = mtCcTaskRunInfoDetService
                        .list(new QueryWrapper<MtCcTaskRunInfoDetEntity>()
                                .eq("task_run_id", mtCcTaskRunInfoEntity.getId())
                                .orderByAsc("create_time"));//该主任务下的所有子任务
                if (mtCcTaskRunInfoDets.size()!=0){
                    for (MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity:mtCcTaskRunInfoDets
                         ) {
                   // MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity = mtCcTaskRunInfoDets.get(0);
                    Integer taskType = mtCcTaskRunInfoDetEntity.getTaskType();
                    String taskDetCode = mtCcTaskRunInfoDetEntity.getTaskDetCode();
                    String doorWay=taskDetCode.substring(1,3);
                    if (doorWay.equals("A1")){
                        doorWay="0001";
                    }
                    if (doorWay.equals("B1")){
                        doorWay="0002";
                    }
                    if (doorWay.equals("A2")){
                        doorWay="0003";
                    }
                    if (doorWay.equals("A3")){
                        doorWay="0004";
                    }
                    if (doorWay.equals("A4")){
                        doorWay="0005";
                    }
                    Integer warehousRankId = mtCcTaskRunInfoDetEntity.getWarehousRankId();
                    String position =String.valueOf(warehousRankId+1000);
                    DDJJobEntity ddjJobEntity=new DDJJobEntity();
                    ddjJobEntity.setType(taskType);//值转换
                    ddjJobEntity.setPosition(Integer.parseInt(doorWay));
                    if (taskType==1){  //1 入库  2 出库
                        ddjJobEntity.setTargetPosition(position);
                        ddjJobEntity.setTakePosition(doorWay);
                    }
                    if (taskType==0){
                        ddjJobEntity.setTargetPosition(doorWay);
                        ddjJobEntity.setTakePosition(position);
                    }
                    //调用堆垛机,本次操作存入日志
                    Integer status = ddjService.sendTaskAndListening(ddjJobEntity);
                    System.err.println("============"+status+"===============");
                    MtCcDeviceCommunLogEntity mtCcDeviceCommunLogEntity=new MtCcDeviceCommunLogEntity();
                    mtCcDeviceCommunLogEntity.setCreateTime(new Date());
                    mtCcDeviceCommunLogEntity.setStatus(0);
                    mtCcDeviceCommunLogEntity.setContent("调用堆垛机，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                    mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogEntity);
                    if (status==-3){
                        MtCcDeviceCommunLogEntity mtCcDeviceCommunLogError=new MtCcDeviceCommunLogEntity();
                        mtCcDeviceCommunLogError.setCreateTime(new Date());
                        mtCcDeviceCommunLogError.setStatus(1);
                        mtCcDeviceCommunLogError.setContent("调用堆垛机失败，IOServer写入异常本次任务重新执行，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                        mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogError);
                        status = ddjService.sendTaskAndListening(ddjJobEntity);//调用堆垛机,本次操作存入日志
                        MtCcDeviceCommunLogEntity mtCcDeviceCommunLog=new MtCcDeviceCommunLogEntity();
                        mtCcDeviceCommunLog.setCreateTime(new Date());
                        mtCcDeviceCommunLog.setStatus(0);
                        mtCcDeviceCommunLog.setContent("本次任务第二次调用堆垛机，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                        mtCcDeviceCommunLogService.save(mtCcDeviceCommunLog);
                    }
                        if (status==-4){

                            message=String.valueOf(ddjJobEntity.getPosition())+"出入口存在障碍物,请移除障碍物并取消任务。";
                            killTask(ddjJobEntity.getPosition());
                            MtCcDeviceCommunLogEntity mtCcDeviceCommunLogError=new MtCcDeviceCommunLogEntity();
                            mtCcDeviceCommunLogError.setCreateTime(new Date());
                            mtCcDeviceCommunLogError.setStatus(1);
                            mtCcDeviceCommunLogError.setContent("调用堆垛机失败，出入库平台有货物，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                            mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogError);
                            status = ddjService.sendTaskAndListening(ddjJobEntity);//调用堆垛机,本次操作存入日志
                            MtCcDeviceCommunLogEntity mtCcDeviceCommunLog=new MtCcDeviceCommunLogEntity();
                            mtCcDeviceCommunLog.setCreateTime(new Date());
                            mtCcDeviceCommunLog.setStatus(0);
                            mtCcDeviceCommunLog.setContent("本次任务第二次调用堆垛机，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                            mtCcDeviceCommunLogService.save(mtCcDeviceCommunLog);
                        }
                    if (status==1){//堆垛机执行成功,改变子任务状态，改变库位信息状态
                        MtCcDeviceCommunLogEntity mtCcDeviceCommunLogSucess=new MtCcDeviceCommunLogEntity();
                        mtCcDeviceCommunLogSucess.setCreateTime(new Date());
                        mtCcDeviceCommunLogSucess.setStatus(1);
                        mtCcDeviceCommunLogSucess.setContent("调用堆垛机成功，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                        mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogSucess);

                        mtCcTaskRunInfoDetEntity.setStatus(2);
                        mtCcTaskRunInfoDetService.updateById(mtCcTaskRunInfoDetEntity);

                        MtCcWarehousPositionRelatLogEntity mtCcWarehousPositionRelatLogEntity=new MtCcWarehousPositionRelatLogEntity();
                        int lengthForCode = mtCcTaskRunInfoDetEntity.getModel().length();//编码长度
                        int productNum=(lengthForCode+1)/10;//该库位上存放的产品有几种
                        if (mtCcTaskRunInfoDetEntity.getTaskType()==0){//出库，库位信息状态改为0空库位，是否被占用改为0可用
                            for (int i = 0; i <productNum ; i++) {
                                String productCode = mtCcTaskRunInfoDetEntity.getModel().substring(10 * i, 10 * i + 9);
                                String[] strings = mtCcTaskRunInfoDetEntity.getNum().split("-");
                                String productQuantity=strings[i];//第i种货物的数量
                                MtCcProductEntity product = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", productCode));
                                MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatService
                                        .getOne(new QueryWrapper<MtCcWarehousPositionRelatEntity>()
                                                .eq("warehous_position_id", warehousRankId).eq("product_id",product.getId()));
                                mtCcWarehousPositionRelatService.removeById(mtCcWarehousPositionRelatEntity);//根据库位id和产品id删除库位详情记录
                                //库位详情日志
                                mtCcWarehousPositionRelatLogEntity.setIsOutIn(0);
                                mtCcWarehousPositionRelatLogEntity.setCreateTime(new Date());
                                mtCcWarehousPositionRelatLogEntity.setProductId(product.getId());
                                mtCcWarehousPositionRelatLogEntity.setQuantity(Integer.parseInt(productQuantity));
                                mtCcWarehousPositionRelatLogEntity.setWarehousPositionId(warehousRankId);
                                mtCcWarehousPositionRelatLogService.save(mtCcWarehousPositionRelatLogEntity);
                            }
                            MtCcWarehousRankEntity mtCcWarehousRankEntity = mtCcWarehousRankService.getById(warehousRankId);
                            mtCcWarehousRankEntity.setIsOccupy(0);
                            mtCcWarehousRankService.updateById(mtCcWarehousRankEntity);//更新rank表状态
                        }else {//入库
                            for (int i = 0; i < productNum; i++) {
                                String productCode = mtCcTaskRunInfoDetEntity.getModel().substring(10 * i, 10 * i + 9);
                                String[] strings = mtCcTaskRunInfoDetEntity.getNum().split("-");
                                String productQuantity=strings[i];//第i种货物的数量
                                MtCcProductEntity product = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", productCode));
                                MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatService
                                        .getOne(new QueryWrapper<MtCcWarehousPositionRelatEntity>()
                                                .eq("warehous_position_id", warehousRankId).eq("product_id",product.getId()));
                                MtCcWarehousRankEntity mtCcWarehousRankEntity = mtCcWarehousRankService.getById(warehousRankId);
                                if (mtCcWarehousPositionRelatEntity!=null){//此次新入库的货物对应的库位详情已经在添加子任务时新建记录，当前只需修改
                                    mtCcWarehousPositionRelatEntity.setStatus(2);
                                    mtCcWarehousPositionRelatService.updateById(mtCcWarehousPositionRelatEntity);
                                }else {//若有回库的货物，新插入货物对应的库位详情记录
                                    MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity1=new MtCcWarehousPositionRelatEntity();
                                    mtCcWarehousPositionRelatEntity1.setCreateTime(new Date());
                                    mtCcWarehousPositionRelatEntity1.setStatus(2);
                                    mtCcWarehousPositionRelatEntity1.setIsOccupy(1);
                                    mtCcWarehousPositionRelatEntity1.setProductId(product.getId());
                                    mtCcWarehousPositionRelatEntity1.setProductName(product.getProductName());
                                    mtCcWarehousPositionRelatEntity1.setQuantity(Integer.parseInt(productQuantity));
                                    mtCcWarehousPositionRelatEntity1.setWarehousPositionId(warehousRankId);
                                    mtCcWarehousPositionRelatEntity1.setWarehousPositionName(mtCcWarehousRankEntity.getAnotherName());
                                    mtCcWarehousPositionRelatService.save(mtCcWarehousPositionRelatEntity1);
                                }
                                //库位详情日志
                                mtCcWarehousPositionRelatLogEntity.setIsOutIn(1);
                                mtCcWarehousPositionRelatLogEntity.setCreateTime(new Date());
                                mtCcWarehousPositionRelatLogEntity.setProductId(product.getId());
                                mtCcWarehousPositionRelatLogEntity.setQuantity(Integer.parseInt(productQuantity));
                                mtCcWarehousPositionRelatLogEntity.setWarehousPositionId(warehousRankId);
                                mtCcWarehousPositionRelatLogService.save(mtCcWarehousPositionRelatLogEntity);
                            }
                        }

                        //新建一条出入库子任务存日志
                        mtCcWarehousPositionRelatLogEntity.setIsOutIn(1);
                        MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity=new MtCcTaskRunInfoDetLogEntity();
                        mtCcTaskRunInfoDetLogEntity.setCreateTime(mtCcTaskRunInfoDetEntity.getCreateTime());
                        mtCcTaskRunInfoDetLogEntity.setWarehousRankId(mtCcTaskRunInfoDetEntity.getWarehousRankId());
                        mtCcTaskRunInfoDetLogEntity.setWarehousRankName(mtCcTaskRunInfoDetEntity.getWarehousRankName());
                        mtCcTaskRunInfoDetLogEntity.setTaskRunId(mtCcTaskRunInfoDetEntity.getTaskRunId());
                        mtCcTaskRunInfoDetLogEntity.setTaskType(mtCcTaskRunInfoDetEntity.getTaskType());
                        mtCcTaskRunInfoDetLogEntity.setStatus(mtCcTaskRunInfoDetEntity.getStatus());
                        mtCcTaskRunInfoDetLogEntity.setTaskDetCode(mtCcTaskRunInfoDetEntity.getTaskDetCode());
                        mtCcTaskRunInfoDetLogEntity.setModel(mtCcTaskRunInfoDetEntity.getModel());
                        mtCcTaskRunInfoDetLogEntity.setNum(mtCcTaskRunInfoDetEntity.getNum());
                        mtCcTaskRunInfoDetLogEntity.setUnit(mtCcTaskRunInfoDetEntity.getUnit());
                        mtCcTaskRunInfoDetLogEntity.setIsHeight(mtCcTaskRunInfoDetEntity.getIsHeight());
                        mtCcTaskRunInfoDetLogEntity.setIsWeight(mtCcTaskRunInfoDetEntity.getIsWeight());
                        mtCcTaskRunInfoDetLogEntity.setRemarks(mtCcTaskRunInfoDetEntity.getRemarks());
                        mtCcTaskRunInfoDetLogService.save(mtCcTaskRunInfoDetLogEntity);

                        Float target_position=ioServerService.getValueByName("Target_Position").r4Val;
                        Float take_position = ioServerService.getValueByName("Take_Position").r4Val;
                        Boolean l_start = ioServerService.getValueByName("L_Start").bitVal;
                        System.out.println("target_position"+target_position+"=====take_position"+take_position);
                        if (!(target_position==0&&take_position==0&&l_start==false)){
                            //IOServer异常，写入日志，报告管理员处理
                            MtCcDeviceCommunLogEntity mtCcDeviceCommunLog=new MtCcDeviceCommunLogEntity();
                            mtCcDeviceCommunLog.setCreateTime(new Date());
                            mtCcDeviceCommunLog.setStatus(0);
                            mtCcDeviceCommunLog.setContent("堆垛机执行任务结束后重置变量失败，IOServer写入异常");
                            mtCcDeviceCommunLogService.save(mtCcDeviceCommunLog);
                        }
                    }
                    else if (status==-2){//堆垛机异常，判断是否重置任务或手动完成任务
                        MtCcDeviceCommunLogEntity mtCcDeviceCommunLogError=new MtCcDeviceCommunLogEntity();
                        mtCcDeviceCommunLogError.setCreateTime(new Date());
                        mtCcDeviceCommunLogError.setStatus(1);
                        mtCcDeviceCommunLogError.setContent("调用堆垛机执行任务途中出现故障，出入库:"+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                        mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogError);
                        Boolean reset_task = ioServerService.getValueByName("Reset_task").bitVal;
                        Boolean submit_task = ioServerService.getValueByName("Submit_task").bitVal;
                        do {
                            reset_task = ioServerService.getValueByName("Reset_task").bitVal;
                            submit_task = ioServerService.getValueByName("Submit_task").bitVal;
                        }while (reset_task==false&&submit_task==false);
                        if (submit_task==true){//手动执行成功
                            ioServerService.setTagValue("Reset_task","88",5);
                            ioServerService.setTagValue("Submit_task","88",5);
                            mtCcTaskRunInfoDetEntity.setStatus(2);
                            mtCcTaskRunInfoDetService.updateById(mtCcTaskRunInfoDetEntity);

                            MtCcWarehousPositionRelatLogEntity mtCcWarehousPositionRelatLogEntity=new MtCcWarehousPositionRelatLogEntity();
                            int lengthForCode = mtCcTaskRunInfoDetEntity.getModel().length();//编码长度
                            int productNum=(lengthForCode+1)/10;//该库位上存放的产品有几种
                            if (mtCcTaskRunInfoDetEntity.getTaskType()==0){//出库，库位信息状态改为0空库位，是否被占用改为0可用
                                for (int i = 0; i <productNum ; i++) {
                                    String productCode = mtCcTaskRunInfoDetEntity.getModel().substring(10 * i, 10 * i + 9);
                                    String[] strings = mtCcTaskRunInfoDetEntity.getNum().split("-");
                                    String productQuantity=strings[i];//第i种货物的数量
                                    MtCcProductEntity product = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", productCode));
                                    MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatService
                                            .getOne(new QueryWrapper<MtCcWarehousPositionRelatEntity>()
                                                    .eq("warehous_position_id", warehousRankId).eq("product_id",product.getId()));
                                    mtCcWarehousPositionRelatService.removeById(mtCcWarehousPositionRelatEntity);//根据库位id和产品id删除库位详情记录
                                    //库位详情日志
                                    mtCcWarehousPositionRelatLogEntity.setIsOutIn(0);
                                    mtCcWarehousPositionRelatLogEntity.setCreateTime(new Date());
                                    mtCcWarehousPositionRelatLogEntity.setProductId(product.getId());
                                    mtCcWarehousPositionRelatLogEntity.setQuantity(Integer.parseInt(productQuantity));
                                    mtCcWarehousPositionRelatLogEntity.setWarehousPositionId(warehousRankId);
                                    mtCcWarehousPositionRelatLogService.save(mtCcWarehousPositionRelatLogEntity);
                                }
                                MtCcWarehousRankEntity mtCcWarehousRankEntity = mtCcWarehousRankService.getById(warehousRankId);
                                mtCcWarehousRankEntity.setIsOccupy(0);
                                mtCcWarehousRankService.updateById(mtCcWarehousRankEntity);//更新rank表状态
                            }else {//入库
                                for (int i = 0; i < productNum; i++) {
                                    String productCode = mtCcTaskRunInfoDetEntity.getModel().substring(10 * i, 10 * i + 9);
                                    String[] strings = mtCcTaskRunInfoDetEntity.getNum().split("-");
                                    String productQuantity=strings[i];//第i种货物的数量
                                    MtCcProductEntity product = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", productCode));
                                    MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity = mtCcWarehousPositionRelatService
                                            .getOne(new QueryWrapper<MtCcWarehousPositionRelatEntity>()
                                                    .eq("warehous_position_id", warehousRankId).eq("product_id",product.getId()));
                                    MtCcWarehousRankEntity mtCcWarehousRankEntity = mtCcWarehousRankService.getById(warehousRankId);
                                    if (mtCcWarehousPositionRelatEntity!=null){//此次新入库的货物对应的库位详情已经在添加子任务时新建记录，当前只需修改
                                        mtCcWarehousPositionRelatEntity.setStatus(2);
                                        mtCcWarehousPositionRelatService.updateById(mtCcWarehousPositionRelatEntity);
                                    }else {//若有回库的货物，新插入货物对应的库位详情记录
                                        MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity1=new MtCcWarehousPositionRelatEntity();
                                        mtCcWarehousPositionRelatEntity1.setCreateTime(new Date());
                                        mtCcWarehousPositionRelatEntity1.setStatus(2);
                                        mtCcWarehousPositionRelatEntity1.setIsOccupy(1);
                                        mtCcWarehousPositionRelatEntity1.setProductId(product.getId());
                                        mtCcWarehousPositionRelatEntity1.setProductName(product.getProductName());
                                        mtCcWarehousPositionRelatEntity1.setQuantity(Integer.parseInt(productQuantity));
                                        mtCcWarehousPositionRelatEntity1.setWarehousPositionId(warehousRankId);
                                        mtCcWarehousPositionRelatEntity1.setWarehousPositionName(mtCcWarehousRankEntity.getAnotherName());
                                        mtCcWarehousPositionRelatService.save(mtCcWarehousPositionRelatEntity1);
                                    }
                                    //库位详情日志
                                    mtCcWarehousPositionRelatLogEntity.setIsOutIn(1);
                                    mtCcWarehousPositionRelatLogEntity.setCreateTime(new Date());
                                    mtCcWarehousPositionRelatLogEntity.setProductId(product.getId());
                                    mtCcWarehousPositionRelatLogEntity.setQuantity(Integer.parseInt(productQuantity));
                                    mtCcWarehousPositionRelatLogEntity.setWarehousPositionId(warehousRankId);
                                    mtCcWarehousPositionRelatLogService.save(mtCcWarehousPositionRelatLogEntity);
                                    Float target_position = ioServerService.getValueByName("Target_Position").r4Val;
                                    Float take_position = ioServerService.getValueByName("Take_Position").r4Val;
                                    Boolean l_start = ioServerService.getValueByName("L_Start").bitVal;
                                    if (!(target_position==0&&take_position==0&&l_start==false)){
                                        //IOServer异常，写入日志，报告管理员处理
                                        MtCcDeviceCommunLogEntity mtCcDeviceCommunLogEntity1=new MtCcDeviceCommunLogEntity();
                                        mtCcDeviceCommunLogEntity1.setCreateTime(new Date());
                                        mtCcDeviceCommunLogEntity1.setStatus(0);
                                        mtCcDeviceCommunLogEntity1.setContent("堆垛机执行任务结束后重置变量失败，IOServer写入异常");
                                        mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogEntity1);
                                    }
                                }
                            }

                            //新建一条出入库子任务存日志
                            mtCcWarehousPositionRelatLogEntity.setIsOutIn(1);
                            MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity=new MtCcTaskRunInfoDetLogEntity();
                            mtCcTaskRunInfoDetLogEntity.setCreateTime(mtCcTaskRunInfoDetEntity.getCreateTime());
                            mtCcTaskRunInfoDetLogEntity.setWarehousRankId(mtCcTaskRunInfoDetEntity.getWarehousRankId());
                            mtCcTaskRunInfoDetLogEntity.setWarehousRankName(mtCcTaskRunInfoDetEntity.getWarehousRankName());
                            mtCcTaskRunInfoDetLogEntity.setTaskRunId(mtCcTaskRunInfoDetEntity.getTaskRunId());
                            mtCcTaskRunInfoDetLogEntity.setTaskType(mtCcTaskRunInfoDetEntity.getTaskType());
                            mtCcTaskRunInfoDetLogEntity.setStatus(mtCcTaskRunInfoDetEntity.getStatus());
                            mtCcTaskRunInfoDetLogEntity.setTaskDetCode(mtCcTaskRunInfoDetEntity.getTaskDetCode());
                            mtCcTaskRunInfoDetLogEntity.setModel(mtCcTaskRunInfoDetEntity.getModel());
                            mtCcTaskRunInfoDetLogEntity.setNum(mtCcTaskRunInfoDetEntity.getNum());
                            mtCcTaskRunInfoDetLogEntity.setUnit(mtCcTaskRunInfoDetEntity.getUnit());
                            mtCcTaskRunInfoDetLogEntity.setIsHeight(mtCcTaskRunInfoDetEntity.getIsHeight());
                            mtCcTaskRunInfoDetLogEntity.setIsWeight(mtCcTaskRunInfoDetEntity.getIsWeight());
                            mtCcTaskRunInfoDetLogEntity.setRemarks(mtCcTaskRunInfoDetEntity.getRemarks());
                            mtCcTaskRunInfoDetLogService.save(mtCcTaskRunInfoDetLogEntity);
                        }else {//重置变量
                            ioServerService.setTagValue("Reset_task","88",5);
                            ioServerService.setTagValue("Submit_task","88",5);
                        }
                    }else {//堆垛机执行任务异常
                        MtCcDeviceCommunLogEntity mtCcDeviceCommunLogEntity1=new MtCcDeviceCommunLogEntity();
                        mtCcDeviceCommunLogEntity1.setCreateTime(new Date());
                        mtCcDeviceCommunLogEntity1.setStatus(0);
                        mtCcDeviceCommunLogEntity1.setContent("堆垛机执行任务过程中出现异常,出入库："+taskType+"起终点"+ddjJobEntity.getTargetPosition()+"-"+ddjJobEntity.getTakePosition()+"任务编码"+mtCcTaskRunInfoDetEntity.getTaskDetCode());
                        mtCcDeviceCommunLogService.save(mtCcDeviceCommunLogEntity1);
                    }
                    }
                    mtCcTaskRunInfoEntity.setStatus(2);
                    mtCcTaskRunInfoService.updateById(mtCcTaskRunInfoEntity);
                    //主任务日志状态更改
                    MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLogEntity = mtCcTaskRunInfoLogService.getOne(new QueryWrapper<MtCcTaskRunInfoLogEntity>().eq("task_code", mtCcTaskRunInfoEntity.getTaskCode()));
                    mtCcTaskRunInfoLogEntity.setStatus(2);
                    mtCcTaskRunInfoLogService.updateById(mtCcTaskRunInfoLogEntity);
                    mtCcTaskRunInfoService.removeById(mtCcTaskRunInfoEntity.getId());
                }else {//主任务下没有子任务，执行完毕
                    mtCcTaskRunInfoEntity.setStatus(2);
                    mtCcTaskRunInfoService.updateById(mtCcTaskRunInfoEntity);
                    //主任务日志状态更改
                    MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLogEntity = mtCcTaskRunInfoLogService.getOne(new QueryWrapper<MtCcTaskRunInfoLogEntity>().eq("task_code", mtCcTaskRunInfoEntity.getTaskCode()));
                    mtCcTaskRunInfoLogEntity.setStatus(2);
                    mtCcTaskRunInfoLogService.updateById(mtCcTaskRunInfoLogEntity);
                    mtCcTaskRunInfoService.removeById(mtCcTaskRunInfoEntity.getId());

                }
            }
        }
    }
}
